import face_recognition
import argparse
def load_and_encode_face(image_path):
    """加载图片并获取人脸编码"""
    image = face_recognition.load_image_file(image_path)
    face_encodings = face_recognition.face_encodings(image)
    if face_encodings:
        return face_encodings[0]
    else:
        raise ValueError("Error")
def compare_faces(known_face_encoding, unknown_face_encoding):
    """比较两个人脸编码并返回相似度百分比"""
    face_distance = face_recognition.face_distance([known_face_encoding], unknown_face_encoding)
    similarity = (1 - face_distance[0]) * 100
    return similarity

def main():
    # 创建解析器

    parser = argparse.ArgumentParser(description="Compare two faces and return similarity percentage.")
    # 添加参数
    parser.add_argument("known_image", help="Path to the known image")
    parser.add_argument("unknown_image", help="Path to the unknown image")
    # 解析命令行参数
    args = parser.parse_args()

    try:
        # 加载并编码已知人脸
        known_face_encoding = load_and_encode_face(args.known_image)
        # 加载并编码未知人脸
        unknown_face_encoding = load_and_encode_face(args.unknown_image)
        # 比较人脸并返回相似度百分比
        similarity = compare_faces(known_face_encoding, unknown_face_encoding)
        print(f"{similarity:.2f}%")

    except ValueError as e:
        print(e)
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()